package com.lagou.tools;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.util.Map;

/**
 *
 */
public class HttpClientUtil {

    public static String doGet(String url) {
        String s = doGet(url,null);
        return s;

    }

    /**
     * get请求 支持request请求方式，不支持restfull方式（了解即可）
     * @param url 请求地址
     * @param param 参数
     * @return 响应字符串
     */
    public static String doGet(String url, Map<String,String> param){
        //创建httpclient对象
        CloseableHttpClient aDefault = HttpClients.createDefault();

        String s = null;
        CloseableHttpResponse response = null;
        try {
            //创建url
            URIBuilder uriBuilder = new URIBuilder(url);

            if(param!=null){
                //在url后面拼接请求参数
                //map本身并不能操作迭代器，需要先变成set集合来操作，这里是操作key当set
                for(String key:param.keySet()){
                    //当前的set，假设对应key的value值，实现拼接
                    uriBuilder.addParameter(key,param.get(key));
                }
            }
            //对应的请求总地址，上面只是操作url的值，如加上http://等等
            URI uri = uriBuilder.build();

            //创建http get请求，并将总地址给他进行请求，使得是get方式
            HttpGet httpGet = new HttpGet(uri);


            //执行请求，并得到响应的结果
            response = aDefault.execute(httpGet);

            //获取响应结果中的状态码
            int statusCode = response.getStatusLine().getStatusCode();

            System.out.println(response); //我这里是：HttpResponseProxy{HTTP/1.1 200 OK [Connection: keep-alive, Content-Type: text/plain, Date: Tue, 26 Jul 2022 02:09:12 GMT, Content-Length: 79] ResponseEntityProxy{[Content-Type: text/plain,Content-Length: 79,Chunked: false]}}
            System.out.println("响应的状态：" +response.getStatusLine()); //响应的状态：HTTP/1.1 200 OK
            System.out.println("响应的状态：" +statusCode); //响应的状态：200

            //200表示响应成功
            if(statusCode==200){
                //响应的内容字符串
                System.out.println(response.getEntity()); //ResponseEntityProxy{[Content-Type: text/plain,Content-Length: 79,Chunked: false]}
                System.out.println("---");
                s = EntityUtils.toString(response.getEntity(),"UTF-8");
                System.out.println(s);
                //我这里是：{"access_token":"59_Fvw_sDU0rnO6tuTiWrP4kONaE41_Fh9oJ5GyNLvrggiINj4WrZyIddJiwSgoaM2dnk1Ds9vshnTP-Wae3UaVzIz3V1giTrbkjU041nXjhRg","expires_in":7200,"refresh_token":"59_4V4PgKjvJ3JAGgRAH46VwqelRNNNgQ2-6FU48jtR98DgTWFWnVuFCMWgN0v5bI1DZ-VCL7a7IVP36dVddV-jkFlZVpLXPj3IW_Zys5P5Z6k","openid":"od4PTw7JYdV2XYGkJPPqF4nZvlfA","scope":"snsapi_login","unionid":"oEg8VuHZxBTgpzcrTi3rAEvwsU88"}
                //若出现类似于这样的：{"errcode":40125,"errmsg":"invalid appsecret, rid: 62df4cc8-00ff426a-331a0ac7"}
                //则代表对应的secret不正确，前端写的是授权作用域，并不是对应的值
                System.out.println("---");
                System.out.println(1);
                //System.out.println(EntityUtils.toString(response.getEntity()));
                // {"access_token":"59_Fvw_sDU0rnO6tuTiWrP4kONaE41_Fh9oJ5GyNLvrggiINj4WrZyIddJiwSgoaM2dnk1Ds9vshnTP-Wae3UaVzIz3V1giTrbkjU041nXjhRg","expires_in":7200,"refresh_token":"59_4V4PgKjvJ3JAGgRAH46VwqelRNNNgQ2-6FU48jtR98DgTWFWnVuFCMWgN0v5bI1DZ-VCL7a7IVP36dVddV-jkFlZVpLXPj3IW_Zys5P5Z6k","openid":"od4PTw7JYdV2XYGkJPPqF4nZvlfA","scope":"snsapi_login","unionid":"oEg8VuHZxBTgpzcrTi3rAEvwsU88"}
                // 虽然UTF-8并没有起作用，但也要防止中文
                //注意EntityUtils.toString(response.getEntity())中EntityUtils.toString()方法只能获得一次，如果再次获得
                //就会报错，自然后面的代码就不会执行，当然也包括他的赋值，即得不到值
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (response != null) {
                    response.close(); //关闭对应的对象，总得也让其他人也能执行请求吧
                }
                aDefault.close(); //关闭对应的对象
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return s;
    }
}
